<?php

namespace app\admin\controller\user;

use app\admin\model\litestore\Litestoregoods;
use app\admin\model\user\UserGoods;
use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 博主申请商品
 *
 * @icon fa fa-circle-o
 */
class UserApplyGoods extends Backend
{

    /**
     * UserApplyGoods模型对象
     * @var \app\admin\model\user\UserApplyGoods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\UserApplyGoods;
        $this->view->assign("stateList", $this->model->getStateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        // 修改where条件
        $filter = json_decode($this->request->get("filter", ''),true);
        $op = json_decode($this->request->get("op", '', 'trim'),true);
        if (isset($filter['createtime'])) {
            $filter['user_apply_goods.createtime'] = $filter['createtime']; // 值
            $op['user_apply_goods.createtime'] = $op['createtime']; // 条件
            unset($filter['createtime'],$op['createtime']); // 删除
        }
        $this->request->get(['filter'=>json_encode($filter,true)]);
        $this->request->get(['op'=>json_encode($op,true)]);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user'=>function($query){
                return $query->withField('nickname');
            },'admin'=>function($query){
                return $query->withField('username');
            }])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑（审核）
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $goods = (new Litestoregoods())::all(['goods_id'=>['in',$row['goods_ids']]],['spec']);
            $goods_info = [];
            foreach($goods as $k=>$v){
                $goods_info[$k]['goods_id'] = $v['goods_id'];
                $goods_info[$k]['goods_name'] = $v['goods_name'];
                $goods_info[$k]['pro_no'] = $v['pro_no'];
                $goods_info[$k]['images'] = cdnurl(explode(",",$v['images'])[0], true);;
                $goods_info[$k]['goods_price'] = $v['spec'][0]['goods_price'];
                $goods_info[$k]['line_price'] = $v['spec'][0]['line_price'];
                $goods_info[$k]['cost_price'] = $v['spec'][0]['cost_price'];
            }
            $row['goods_info'] = array_values($goods_info);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        $now_user_goods = (new UserGoods())->where('user_id',$row['user_id'])->where('deletetime is null')->column('goods_id');
        //检查是否所有商品都已设置分佣
        $t = time();
        if($params['state'] == 2) {
            $add_goods = [];
            foreach ($params['goods_info'] as $k=>$v){
                if (in_array($k, $now_user_goods)) {
                    $this->error(__('GoodsId:' . $k . ', the product library of this blogger already exists', ''));
                }
                if(floatval($v) <= 0 || floatval($v) > 100){
                    $this->error(__('Blogger_rate is between (0~100)', ''));
                }
                $add_goods[] = [
                    'user_id'=>$row['user_id'],
                    'goods_id'=>$k,
                    'blogger_rate'=>$v,
                    'createtime'=>$t,
                    'updatetime'=>$t,
                ];
            }
        }elseif($params['state'] == 3){
            if(empty($params['desc'])){
                $this->error(__('Review comments cannot be blank', ''));
            }
        }else{
            $this->error(__('Please select the approval status', ''));
        }
        $params['admin_id'] = $this->auth->id;
        $params['checktime'] = $t;
        $params['goods_info'] = json_encode($params['goods_info']);

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            //如果审核通过，将申请的商品写入博主商品库中
            if($params['state'] == 2 && !empty($add_goods)){
                (new UserGoods())->insertAll($add_goods);
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 审核商品详情
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $goods = (new Litestoregoods())::all(['goods_id'=>['in',$row['goods_ids']]],['spec']);
        $goods_info_old = json_decode($row['goods_info'],true);
        $goods = array_column(object2array($goods),null,'goods_id');
        $goods_info = [];
        foreach($goods_info_old as $k=>$v){
            $goods_info[$k]['goods_id'] = $k;
            $goods_info[$k]['goods_name'] = $goods[$k]['goods_name'];
            $goods_info[$k]['pro_no'] = $goods[$k]['pro_no'];
            $goods_info[$k]['images'] = cdnurl(explode(",",$goods[$k]['images'])[0], true);;
            $goods_info[$k]['goods_price'] = $goods[$k]['spec'][0]['goods_price'];
            $goods_info[$k]['line_price'] = $goods[$k]['spec'][0]['line_price'];
            $goods_info[$k]['cost_price'] = $goods[$k]['spec'][0]['cost_price'];
            $goods_info[$k]['blogger_rate'] = $v;
        }
        $row['goods_info'] = array_values($goods_info);

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
}
